package com.nf.mvc.argument;

import com.nf.mvc.HandlerContext;
import com.nf.mvc.MethodArgumentResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Parameter;

public class ServletApiMethodArgumentResolver implements MethodArgumentResolver {
    @Override
    public boolean supports(Parameter parameter) {
        //得到方法的参数的类型 ，比如String，HttpServletRequest
        Class<?> type = parameter.getType();
        if (HttpServletRequest.class.isAssignableFrom(type)
                || HttpServletResponse.class.isAssignableFrom(type)
                || HttpSession.class.isAssignableFrom(type)
                || ServletContext.class.isAssignableFrom(type)) {
            return true;
        }
        return false;

    }

    @Override
    public Object resolveArgument(Parameter parameter, HttpServletRequest request) throws Exception {
        Class<?> type = parameter.getType();

        if (HttpServletRequest.class.isAssignableFrom(type)) {
            return request;
        }
        if (HttpServletResponse.class.isAssignableFrom(type)) {
            return HandlerContext.getContext().getResponse();
        }
        if (HttpSession.class.isAssignableFrom(type)) {
            return request.getSession();
        }
        if (ServletContext.class.isAssignableFrom(type)) {
            return request.getServletContext();
        }
        return null;
    }
}
